<template>
  <div style="margin-top: 2vh">
    <div style="background-color: white; width: 68vw; margin: auto;">
      <!-- 上方标题 -->
      <div style="border-bottom: 1px solid #e9e9e9; height: 7vh; width: 100%;">
        <span style="font-weight: bold; font-size: 1.1rem; line-height: 7vh; margin-left: 1.5vw;">软件著作权</span>
      </div>

      <pdf-preview :pdf-url="form.pdfUrl"></pdf-preview>
    </div>

    <!-- 填写信息 -->
    <div style="background-color: white; width: 68vw; margin: auto; display: flex; flex-direction: column; padding-bottom: 5vh; margin-top: 3vh">
      <div style="flex: 1;">
        <div style="border-bottom: 1px solid #e9e9e9; height: 7vh;">
          <span style="font-weight: bold; font-size: 1.1rem; line-height: 7vh; margin-left: 1.5vw">信息详情</span>
        </div>
        <div>
          <el-form :model="form" :rules="rules" ref="formRef" label-width="100px" style="margin-top: 5vh">
            <el-form-item label="著作权名称" prop="title" required>
              <el-input v-model="form.title" placeholder="请输入软件著作权名称" style="width: 34vw;"></el-input>
            </el-form-item>

            <el-form-item label="证书号" prop="certificateNo" required>
              <el-input v-model="form.certificateNo" placeholder="请输入证书号" style="width: 34vw;"></el-input>
            </el-form-item>

            <el-form-item label="本人排名" prop="authorRank" required>
              <el-select v-model="form.authorRank" placeholder="请选择排名" style="width: 34vw;">
                <el-option
                    v-for="i in 10"
                    :key="i"
                    :label="i.toString()"
                    :value="i">
                </el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="开发完成时间" prop="finishTime">
              <el-date-picker
                  v-model="form.finishTime"
                  type="date"
                  placeholder="选择日期"
                  format="YYYY-MM-DD"
                  value-format="x"
                  style="width: 34vw;"
              ></el-date-picker>
            </el-form-item>

            <el-form-item label="获得时间" prop="puttime" required>
              <el-date-picker
                  v-model="form.puttime"
                  type="date"
                  placeholder="选择日期"
                  format="YYYY-MM-DD"
                  value-format="x"
                  style="width: 34vw;"
              ></el-date-picker>
            </el-form-item>

            <el-form-item label="登记号" prop="registerNo">
              <el-input v-model="form.registerNo" placeholder="请输入登记号" style="width: 34vw;"></el-input>
            </el-form-item>

            <el-form-item label="著作权类型" prop="copyrightType">
              <el-radio-group v-model="form.copyrightType">
                <el-radio label="计算机软件">软件制品</el-radio>
                <el-radio label="音像制品">音像制品</el-radio>
              </el-radio-group>
            </el-form-item>

            <el-form-item label="著作权人" prop="copyrightOwner" required>
              <el-input v-model="form.copyrightOwner" placeholder="请输入著作权人" style="width: 34vw;"></el-input>
            </el-form-item>

            <el-form-item label="备注信息" prop="description">
              <el-input
                  type="textarea"
                  v-model="form.description"
                  :rows="4"
                  placeholder="请输入备注信息"
                  style="width: 34vw;"
              ></el-input>
            </el-form-item>

            <!-- 作者信息表格 -->
            <el-form-item label="作者信息" prop="authorInfo">
              <div style="background-color: #f9f9f9; width: 55vw; height: auto;">
                <ul style="display: flex; list-style-type: none; padding: 0; margin: 0; line-height: 6vh; color: #3f3f3f">
                  <li style="margin-left: 1.5vw">排序</li>
                  <li style="margin-left: 3vw">姓名</li>
                  <li style="margin-left: 3.5vw">作者身份</li>
                  <li style="margin-left: 5vw">单位名称</li>
                </ul>

                <div v-for="(author, index) in form.authorInfo" :key="index" style="margin-top: 1vh; display: flex; align-items: center;">
                  <el-select style="width: 4vw;" v-model="author.rank" placeholder="排序">
                    <el-option
                        v-for="i in 10"
                        :key="i"
                        :label="i.toString()"
                        :value="i"
                    ></el-option>
                  </el-select>

                  <el-input v-model="author.name" style="width: 5vw; margin-left: 1vw" placeholder="姓名"></el-input>

                  <el-select style="width: 5.5vw; margin-left: 1vw" v-model="author.identity" placeholder="身份">
                    <el-option label="老师" value="老师"></el-option>
                    <el-option label="博士生" value="博士生"></el-option>
                    <el-option label="硕士生" value="硕士生"></el-option>
                    <el-option label="本科生" value="本科生"></el-option>
                  </el-select>



                  <el-input v-model="author.institution" style="width: 15vw; margin-left: 3vw" placeholder="单位名称"></el-input>
                </div>
              </div>
            </el-form-item>

            <el-form-item label="关联课题" prop="projectId">
              <el-select v-model="form.projectId" placeholder="请选择关联课题" style="width: 34vw;">
                <el-option label="暂无课题" value=""></el-option>
              </el-select>
            </el-form-item>
          </el-form>

          <div style="display: flex; justify-content: center; margin-top: 2vh">
            <button @click="submitForm" class="upload-button" style="width: 10vw;">返 回</button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>


<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'

import { useRoute, useRouter } from 'vue-router'
import PdfPreview from "@/components/result/PdfPreview.vue";
import { getCopyRightById } from "@/api/result/copyright.js";
import { getProjectNameById } from "@/api/result/longitudinalProjects";

const route = useRoute()
const router = useRouter()
const formRef = ref(null)

// 表单数据
const form = reactive({
  id: '',
  title: '',
  certificateNo: '',
  authorRank: undefined,
  finishTime: '',
  puttime: '',
  registerNo: '',
  copyrightType: '计算机软件',
  copyrightOwner: '',
  description: '',
  syncStatus: '',
  projectId: '',
  pdfPath: '',
  authorInfo: [{
    name: '',
    rank: 1,
    identity: '',
    institution: '',
    coFirstAuthor: false,
    corresponding: false
  }]
})

// 表单验证规则
const rules = {
  title: [{ required: true, message: '请输入著作权名称', trigger: 'blur' }],
  certificateNo: [{ required: true, message: '请输入证书号', trigger: 'blur' }],
  authorRank: [{ required: true, message: '请选择本人排名', trigger: 'change' }],
  puttime: [{ required: true, message: '请选择获得时间', trigger: 'change' }],
  copyrightOwner: [{ required: true, message: '请输入著作权人', trigger: 'blur' }]
}

// 添加作者
const addAuthor = () => {
  form.authorInfo.push({
    name: '',
    rank: form.authorInfo.length + 1,
    identity: '',
    institution: '',
    coFirstAuthor: false,
    corresponding: false
  })
}

// 删除作者
const removeAuthor = (index) => {
  form.authorInfo.splice(index, 1)
}

// 提交表单
const submitForm = async () => {
  router.push("/result/copyright");
}

// 安全转换日期为时间戳（避免NaN）
const parseDateToTimestamp = (dateStr) => {
  if (!dateStr) return null;
  // 处理后端返回的日期字符串（如"2025-07-30"）
  const date = new Date(dateStr);
  // 验证日期有效性
  if (isNaN(date.getTime())) {
    console.warn(`无效的日期格式: ${dateStr}`);
    return null;
  }
  return date.getTime(); // 返回时间戳（毫秒）
}

// 获取详情数据
onMounted(async () => {
  const id = route.query.id
  if (id) {
    try {
      const res = await getCopyRightById(id)
      console.log("res", res)
      if (res.code === 200 && res.data) {
        const data = res.data;
        // 处理日期字段，避免NaN
        data.finishTime = parseDateToTimestamp(data.finishTime);
        data.puttime = parseDateToTimestamp(data.puttime);

        // 处理作者信息默认值（避免undefined导致的绑定问题）
        if (!data.authorInfo || !data.authorInfo.length) {
          data.authorInfo = [{
            name: '',
            rank: 1,
            identity: '',
            institution: '',
            coFirstAuthor: false,
            corresponding: false
          }];
        } else {
          // 为每个作者补充默认值
          data.authorInfo.forEach(author => {
            author.coFirstAuthor = author.coFirstAuthor || false;
            author.corresponding = author.corresponding || false;
          });
        }

        Object.assign(form, data);
      } else {
        ElMessage.error('获取数据失败')
      }
    } catch (error) {
      console.error('获取数据失败:', error)
      ElMessage.error('获取数据失败，请重试')
    }
  }
})
</script>

<style scoped>
.upload-button {
  color: white;
  height: 3.8vh;
  width: 6.5vw;
  background-color: #00b38a;
  cursor: pointer;
  border: none;
}

.upload-button:hover {
  background-color: #009b77;
}

canvas {
  display: block;
  margin: 0 auto;
  background: white;
  box-shadow: 0 1px 3px 0 rgb(0 0 0 / 0.1);
  transform-origin: top center;
}

.header h2 {
  margin: 0;
  font-size: 24px;
  font-weight: bold;
}

.thumbnail-wrapper canvas {
  width: 100%;
  height: auto;
  border-radius: 4px;
}

.thumbnail-wrapper:hover .delete-btn {
  opacity: 1;
}

.toolbar button {
  padding: 0.5rem;
  border: none;
  background: transparent;
  border-radius: 4px;
  cursor: pointer;
  color: #4b5563;
}

.toolbar button:hover {
  background: #f3f4f6;
}

.toolbar button:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.canvas-container canvas {
  background: white;
  box-shadow: 0 1px 3px 0 rgb(0 0 0 / 0.1);
  transform-origin: top center;
}
</style>
